<template>
  <div class="app-container">
    <iframe ref="iframeRef" @load="onIframeLoad" frameborder="0" style="height: 100%"></iframe>
  </div>
</template>

<script lang="ts" setup>
import WorkflowApi from "@/api/workflow";
import { getAccessToken, getRefreshToken, setToken } from "@/utils/cacheUtils";
const iframeRef = ref<HTMLIFrameElement | null>(null);
onMounted(async () => {
  iframeRef.value.src = await WorkflowApi.GetIndexUrl();
});

const messageType = "token";
const onIframeLoad = async () => {
  // 向iframe页面传递token
  // 使用postMessage发送token给iframe
  if (iframeRef.value && iframeRef.value.contentWindow) {
    const accessToken = getAccessToken();
    const refreshToken = getRefreshToken();
    const iframeOrigin = new URL(iframeRef.value.src).origin;
    iframeRef.value.contentWindow.postMessage(
      {
        messageType: messageType,
        accessToken: accessToken,
        refreshToken: refreshToken,
      },
      iframeOrigin
    ); // 指定目标源
  }
};

// 监听来自iframe的消息
window.addEventListener(
  "message",
  function (event) {
    // 检查消息来源，确保它来自受信任的iframe源
    const iframeOrigin = new URL(iframeRef.value.src).origin;
    if (event.origin != iframeOrigin) {
      return;
    }
    if (event.data && event.data.messageType === messageType) {
      // 处理消息
      const accessToken = event.data.accessToken;
      const refreshToken = event.data.refreshToken;
      // 将新token保存到localStorage中
      setToken(accessToken, refreshToken);
    }
  },
  false
);
</script>

<style>
.app-container {
  height: 100%;
  display: -webkit-box;
  display: -moz-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-orient: vertical;
  -webkit-box-direction: normal;
  -webkit-flex-direction: column;
  -moz-box-orient: vertical;
  -moz-box-direction: normal;
  -ms-flex-direction: column;
  flex-direction: column;
}
</style>
